﻿using System.Linq;
using System.Web.Mvc;
using SportClubMvc.Model;
using SportClubMvc.Model.SportsClubClasses;

namespace SportClubMvc.Controllers
{
    public class SkateController : Controller
    {
        private readonly SportsClubDbContext _dbContext = new SportsClubDbContext();

        public ActionResult Index()
        {
            var members = _dbContext.Members.ToList();
            return View(members);
        }

        public PartialViewResult Edit(int skaterId)
        {
            var memberModel = _dbContext.Members.Where(x => x.Id == skaterId).FirstOrDefault();
            return PartialView(memberModel);
        }

        [HttpPost]
        public PartialViewResult Edit(MemberModel model)
        {
            if (ModelState.IsValid)
            {
                var memberToUpdate = _dbContext.Members.Where(x => x.Id == model.Id).FirstOrDefault();
                _dbContext.Entry(memberToUpdate).CurrentValues.SetValues(model);
                _dbContext.SaveChanges();    
            }

            return PartialView("SkaterView", model);
        }

        public PartialViewResult Add()
        {
            var memberModel = new MemberModel();

            return PartialView(memberModel);
        }

        [HttpPost]
        public RedirectToRouteResult Add(MemberModel model)
        {
            if (ModelState.IsValid)
            {
                _dbContext.Members.Add(model);
                _dbContext.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        public PartialViewResult SkaterView(MemberModel model)
        {
            return PartialView(model);
        }
        
        public ActionResult Delete(int skaterId)
        {
            var memberModel = _dbContext.Members.Where(x => x.Id == skaterId).FirstOrDefault();
            _dbContext.Members.Remove(memberModel);
            _dbContext.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
